/**
 * 定义F基类
 */
// 在页面中显示日志
function log(text) {
    var logEl = window.logEl;

    if (!logEl) {
        logEl = $('<div style="font-size: 18px; line-height: 1.3em; padding: 10px;"></div>');
        logEl.appendTo('body');
        window.logEl = logEl;
    }

    logEl.append('<p>' + text + '</p>');
}

(function () {
// 并发请求数
    window.requestCount = 0;
    var loginoutForwardFlag = true,
        requestFinishTimeout = null;
    /**
     * 不允许关闭loading动画的页面列表
     *
     * {
     *    html:'test/test.html',
     *    msg: '正在交易中请耐心等待.'
     * }
     *
     * @type {Array}
     */
    var cannotStopLoadingList = [{
        "url":'login/login.html',
        "msg":""
    }];

    $class('XX').via(function () {

        var templates = {};
        this.callbacks = {};
        this.events = {};
        this.handlers = {};
        this.queryMap = $$.getQueryMap();
        this.time = 59;
        this.timeClickFlag = true;//防重复点击
        /**
         * 构造函数
         */
        this.construct = function (root) {
            var self = this,
                handlers = this.handlers,
                start,
                event,
                selector;
            // 解析事件声明
            root = root ? $(root) : $('body');
            self.$root = root;
            _.each(this.events, function (handlerName, expression) {
                start = expression.indexOf(' ');
                event = expression.substring(0, start);
                selector = expression.slice(start - expression.length + 1);

                root.delegate(selector, event, (function () {
                    var handler = handlers[handlerName];
                    if(handler){
                        return function (event) {
                            handler.apply(self, [event, $(this)]);
                        };
                    }
                })());
            });
        };

        /**
         * 发送HTTP请求
         * @param options
         */
        this.request = function (options) {
            var success = options.success, // 成功回调
                self = this,
                loading = (options.loading === undefined) ? true : !!options.loading,
                callback = null;
            options = F.requestOptions(options);
            // 成功回调函数
            if (success) {
                if (typeof success == 'string') {
                    callback = _.bind(this.callbacks[options.success], self);
                    options.success = function (response) {

                        if (loading && requestCount > 0) {
                            requestCount--;

                            if (requestCount === 0) {
                                // 在最后一个请求完成后隐藏加载动画
                                requestFinishTimeout = setTimeout(function () {
                                    requestFinishTimeout = null;
                                    $$.Native.loadingFinish();
                                }, 300);
                            }
                        }

                        if (typeof(response) === 'string') {
                            try {
                                response = JSON.parse(response);
                            } catch (e) {
                                response = {
                                    retCode: '000001'
                                };
                            }
                        }
                        if (response !== null) {
                            if (response.retCode === '000000') {

                                // 如果台州返回登录超时或者会话超时时设置userInfo为null, 跳转到登录页面。
                                // 重复登陆被踢掉的code与会话超时的code一致处理也一致
                                if (response.responseBody && (response.responseBody.ReturnCode == "role.invalid_user" || response.responseBody.ReturnCode == "response.responseBody.ReturnCode")) {

                                    $$.Native.updateTab([{id:'BANK',text:'网银'}]);
                                    // 会话超时时清除所有的数据库的key。除了任意门的数据
                                    $$.Native.clearAppointData({
                                        data: ['ANY_DOOR_DATA'],
                                        callback: function(){
                                            var list = [
                                                    "main/homePage.html"
                                                ],
                                                loginoutFlag = true;//登录超时白名单
                                            _.each(list, function (item) {
                                                if (location.href.indexOf(item) != "-1") {
                                                    loginoutFlag = false;

                                                }
                                            });
                                            if(loginoutForwardFlag && loginoutFlag){
                                                loginoutForwardFlag = false;
                                                $$.Native.back({
                                                    'url': 'main/homePage.html'
                                                });
                                            }
                                        }
                                    });
                                    $$.Native.logoutCallAnyDoor();
                                }

                                callback(response.responseBody);
                            } else if (!_.isEmpty(response.retMsg)) {
                                $$.Native.tip({text: response.retMsg});
                            } else {
                                $$.Native.tip({text: '系统繁忙!请稍后重试'});
                            }
                        }
                    };
                } else {
                    var successCallback = success;

                    options.success = function (response) {
                        if (loading && requestCount > 0) {
                            requestCount--;

                            if (requestCount === 0) {
                                // 在最后一个请求完成后隐藏加载动画
                                requestFinishTimeout = setTimeout(function () {
                                    requestFinishTimeout = null;
                                    $$.Native.loadingFinish();
                                }, 300);
                            }
                        }
                        successCallback(response);
                    };
                }

                if (loading) {
                    if (requestCount === 0) {
                        // 在第一个请求中显示加载动画
                        if (requestFinishTimeout) {
                            clearTimeout(requestFinishTimeout);
                        } else {
                            var isCancel = true;
                            var nowHtml = location.href;
                            var msg = '';
                            if(cannotStopLoadingList.length > 0 ){
                                _.each(cannotStopLoadingList,function(item){
                                    if(nowHtml.indexOf(item.url) != -1){
                                        isCancel = false;
                                        msg = item.msg;
                                        return;
                                    }
                                });
                            }
                            if(!isCancel){
                                $$.Native.loadingBegin({isCancel:isCancel, msg: msg});
                            }else{
                                $$.Native.loadingBegin();
                            }
                        }
                    }
                    requestCount++;
                }
            } else {
                options.success = function (response) {
                    $$.Native.loadingFinish();
                };
            }
            var error = function (response) {
                if (self.requestCount <= 0) {
                    $$.Native.loadingFinish();
                }
                if (response.code == '1') {
                    $$.Native.tip({text: "请求失败"});
                }
            };
            options.error = options.error || error;
            // 失败回调函数
            if (options && options.error && typeof error == 'string') {
                callback = _.bind(this.callbacks[options.error], self);
            }
            $$.Native.request(options);
        };
        /**
         * 渲染模版数据
         * @param name 模版名称
         * @param data 渲染数据
         * @param element 渲染容器
         * @returns {String}
         */
        this.render = function (id, data, element) {
            var tpl = templates[id], html;
            if (!tpl) {
                tpl = _.template($('#' + id).html());
                templates[id] = tpl;
            }
            html = tpl(data);
            if (element) {
                $(element).html(html);
                // 渲染模板完成后，重新执行关联input邻近的label标签
            }
            return html;
        };
    });
})();